//
//  MyPaymentViewController.m
//  Article
//
//  Created by 徐番茄丶 on 16/5/16.
//  Copyright © 2016年 mac. All rights reserved.
//

#import "MyPaymentViewController.h"
#import "MyTools.h"
#import "MyPaymentTableViewCell.h"
#import <StoreKit/StoreKit.h>

@interface MyPaymentViewController ()
<UITableViewDelegate,
UITableViewDataSource,
UIAlertViewDelegate,
SKPaymentTransactionObserver,
SKProductsRequestDelegate>{
    UIButton *_wxbtn;
    UIButton *_zfbbtn;
    UIButton *_apbtn;
    
    int _howPay;
    
    NSString *_vipID;
    NSString *_vipCost;
    
    NSString *_product;
}

@end

@implementation MyPaymentViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"购买会员";
    
    self.navigationItem.leftBarButtonItem = [[UIBarButtonItem alloc]initWithImage:[UIImage imageNamed:@"arrow"] style:UIBarButtonItemStylePlain target:self action:@selector(back)];
    [self.navigationItem.leftBarButtonItem setTintColor:UIColorFromRGB(0xffffff)];
    
    self.view.backgroundColor = UIColorFromRGB(0xefeff1);
    
    [self creatView];
}
-(void)creatView{
    
    [self requestVipInfo];
    
    UIView *herdview = [[UIView alloc]initWithFrame:CGRectMake(0, 0, WIDTH, HEIGHT/5)];
    herdview.backgroundColor = [UIColor whiteColor];
    [self.view addSubview:herdview];
    
    
    UITableView *mytab = [[UITableView alloc]initWithFrame:CGRectMake(0, HEIGHT/5 + 20, WIDTH, 180)];
    //mytab.backgroundColor = [UIColor whiteColor];
    mytab.separatorStyle = UITableViewCellStyleDefault;
    mytab.showsVerticalScrollIndicator = NO;
    mytab.rowHeight = 60 * MYWIDTH;
    mytab.delegate = self;
    mytab.dataSource = self;
    mytab.scrollEnabled = NO;
    [self.view addSubview:mytab];
    
    
    UIButton *paybtn = [[UIButton alloc]initWithFrame:CGRectMake(50 *MYWIDTH, HEIGHT/5 + 200 + 40, 275 *MYWIDTH, 40 * MYHEIGHT)];
    paybtn.layer.cornerRadius = 5;
    paybtn.backgroundColor = UIColorFromRGB(0xff6a6a);
    [paybtn setTitle:@"确认支付 ￥298" forState:UIControlStateNormal];
    [paybtn setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    [paybtn addTarget:self action:@selector(payment) forControlEvents:UIControlEventTouchUpInside];
    [self.view addSubview:paybtn];
    
    
}

#pragma mark选择支付方式
-(void)payment{
    NSString *str = [[NSString alloc]init];
    if (_howPay == 0) {
        //微信支付
        str = @"wx";
        [self pay:str];
    }else if (_howPay == 1){
        //支付宝支付
        str = @"alipay";
        [self pay:str];
    }else if (_howPay == 2){
        //苹果内购
        UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"确认使用苹果内购方式进行购买会员？" delegate:self cancelButtonTitle:@"取消" otherButtonTitles:@"确认", nil];
        [alert show];
    }
    
}
//获取支付参数
-(void)pay:(NSString *)str{
    UIAlertController *ac = [UIAlertController alertControllerWithTitle:@"提示" message:@"你确定要去付款" preferredStyle:UIAlertControllerStyleAlert];
    UIAlertAction * aa = [UIAlertAction actionWithTitle:@"前往" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
        [ac dismissViewControllerAnimated:YES completion:nil];
        
        NSUserDefaults *user = [NSUserDefaults standardUserDefaults];
        NSString *urlstr = VIP_TOUP_URL;
        NSDictionary *dic = @{@"user_token":[user objectForKey:@"token"],
                              @"channel":str,//支付类型
                              @"rank_id":@"10"};
        
        AFHTTPRequestOperationManager *manager=[AFHTTPRequestOperationManager manager];
        manager.responseSerializer=[AFHTTPResponseSerializer serializer];
        
        [MBProgressHUD showHUDAddedTo:self.view animated:YES];
        
        
        [manager POST:urlstr parameters:dic success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            NSDictionary *dic1 = [NSJSONSerialization JSONObjectWithData:responseObject options:NSJSONReadingAllowFragments error:nil];
            //NSLog(@"///%@",dic1);
            
            if ([[dic1 objectForKey:@"status"] intValue] == 0) {
                [self.view makeToast:[dic1 objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
                
            }else{
                
                if ([str isEqualToString:@"alipay"]) {
                    
                    [self alipay:dic1];
                    
                }else{
                    [self wxpay:dic1];
                }
            }
        } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
            //NSLog(@"=====>%@",error);
            [MBProgressHUD hideHUDForView:self.view animated:YES];
            
            if ([MyTools connectedToNetwork] == 0) {
                [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
            }else{
                [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
            }
            
        }];
        
    }];
    UIAlertAction *other = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleDefault handler:^(UIAlertAction *action) {
        
    }];
    [ac addAction:other];
    [ac addAction:aa];
    [self presentViewController:ac animated:YES completion:nil];
}
#pragma mark 支付宝支付
-(void)alipay:(NSDictionary *)dic{
    NSString *alipaystrUrl = @"appyrgiug56hy53g2h64t6";
    
    //NSLog(@"---%@",dic);
    //支付宝显示网页版
    self.views = [[UIApplication sharedApplication] windows];
    UIWindow* windowtemp = _views[0];
    
    if (windowtemp.hidden) {
        windowtemp.hidden = NO;
    }
    else
    {
        NSLog(@"no hidden");
    }
    if ([[UIApplication sharedApplication] canOpenURL:[NSURL URLWithString:@"alipay://"]]) {
        
        windowtemp.hidden = YES;
    }
    //跳转支付宝
    
    [Pingpp createPayment:[dic objectForKey:@"data"]
           viewController:self
             appURLScheme: alipaystrUrl
           withCompletion:^(NSString *result, PingppError *error) {
               windowtemp.hidden = YES;
               
               if ([result isEqualToString:@"success"]) {
                   // 支付成功
                   
                   NSLog(@"成功");
                   
                   
               } else {
                   // 支付失败或取消
                   NSLog(@"Error: code=%lu msg=%@", (unsigned long)error.code, [error getMsg]);
               }
           }
     ];
    
}
#pragma mark 微信支付
-(void)wxpay:(NSDictionary *)dic{
    
}




#pragma mark tableview代理
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return 3;
}
-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    static NSString  *identifier = @"cell";
    MyPaymentTableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:identifier];
    if (cell == nil) {
        cell = [[MyPaymentTableViewCell alloc]initWithStyle:UITableViewCellStyleDefault reuseIdentifier:identifier];
        //cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
    }
    if (indexPath.row == 0) {
        cell.imagelab.text = @"\U0000e614";
        cell.imagelab.textColor = UIColorFromRGB(0x00BB7E);
        cell.titlelab.text = @"微信支付";
        cell.messagelab.text = @"推荐安装微信5.0及以上版本的用户使用";
        
        
        _wxbtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 50, 15, 30, 30)];
        _wxbtn.tag = indexPath.row;
//        _wxbtn.titleLabel.font = [UIFont fontWithName:@"IconFont" size: 20 * MYWIDTH];
//        [_wxbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        [_wxbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_wxbtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:_wxbtn];
    }else if (indexPath.row == 1){
        cell.imagelab.text = @"\U0000e60b";
        cell.imagelab.textColor = UIColorFromRGB(0x249ADA);
        cell.titlelab.text = @"支付宝支付";
        cell.messagelab.text = @"推荐有支付宝账号的用户使用";
        
        _zfbbtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 50, 15, 30, 30)];
        _zfbbtn.tag = indexPath.row;
//        _zfbbtn.titleLabel.font = [UIFont fontWithName:@"IconFont" size: 20 * MYWIDTH];
//        [_zfbbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_zfbbtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:_zfbbtn];
    }else if (indexPath.row == 2){
        cell.imagelab.text = @"\U0000e60c";
        cell.imagelab.font = [UIFont fontWithName:@"IconFont" size: 26 * MYWIDTH];
        cell.imagelab.textColor = [UIColor blackColor];
        cell.titlelab.text = @"苹果内购买";
        cell.messagelab.text = @"推荐iPhone用户使用";
        
        _apbtn = [[UIButton alloc]initWithFrame:CGRectMake(WIDTH - 50, 15, 30, 30)];
        _apbtn.tag = indexPath.row;
//        _apbtn.titleLabel.font = [UIFont fontWithName:@"IconFont" size: 20 * MYWIDTH];
//        [_apbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_apbtn addTarget:self action:@selector(btnClick:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:_apbtn];
    }
    
    
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (indexPath.row == 0) {
        _howPay = 0;
        [_wxbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
    }else if (indexPath.row == 1){
        _howPay = 1;
        [_wxbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
    }else if (indexPath.row == 2){
        _howPay = 2;
        [_wxbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
    }
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
}

-(void)btnClick:(UIButton *)btn{
    if (btn.tag == 0) {
        _howPay = 0;
        [_wxbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
    }else if (btn.tag == 1){
        _howPay = 1;
        [_wxbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
    }else if (btn.tag == 2){
        _howPay = 2;
        [_wxbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_zfbbtn setImage:[UIImage imageNamed:@"未选中"] forState:UIControlStateNormal];
        [_apbtn setImage:[UIImage imageNamed:@"选中"] forState:UIControlStateNormal];
//        [_wxbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_wxbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_zfbbtn setTitle:@"\U0000e610" forState:UIControlStateNormal];
//        [_zfbbtn setTitleColor:UIColorFromRGB(0x999999) forState:UIControlStateNormal];
//        [_apbtn setTitle:@"\U0000e60d" forState:UIControlStateNormal];
//        [_apbtn setTitleColor:UIColorFromRGB(0x1DE3DD) forState:UIControlStateNormal];
    }
    
}

#pragma mark 请求参数
- (void)requestVipInfo{
    
    AFHTTPRequestOperationManager *manager = [MyTools initAFHttpManager];
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    
    [manager POST:@"http://wz.ijiaque.com/app/toup/vip_info.html" parameters:nil success:^(AFHTTPRequestOperation * _Nonnull operation, id  _Nonnull responseObject) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        if ([[responseObject objectForKey:@"status"] intValue] == 1) {
            NSLog(@"%@",[responseObject objectForKey:@"data"]);
            _vipID = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"][0] objectForKey:@"id"]];
            _vipCost = [NSString stringWithFormat:@"%@",[[responseObject objectForKey:@"data"][0] objectForKey:@"cost"]];
            
        }else{
            [self.view makeToast:[responseObject objectForKey:@"info"] duration:1.0 position:CSToastPositionCenter];
        }
        
    } failure:^(AFHTTPRequestOperation * _Nullable operation, NSError * _Nonnull error) {
        [MBProgressHUD hideAllHUDsForView:self.view animated:YES];
        
        if ([MyTools connectedToNetwork] == 0) {
            [self.view makeToast:@"请检查是否联网" duration:1.0 position:CSToastPositionCenter];
        }else{
            [self.view makeToast:@"服务器错误，再试一次" duration:1.0 position:CSToastPositionCenter];
        }
    }];
}

#pragma mark 苹果内购
-(void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex{
    if (buttonIndex == 1) {
        
        [[SKPaymentQueue defaultQueue] addTransactionObserver:self];
        _product = @"com.thumb12341";
        if([SKPaymentQueue canMakePayments]){
            [self requestProductData:_product];
        }else{
            NSLog(@"不允许程序内付费");
        }
    }
}
//请求商品
- (void)requestProductData:(NSString *)type{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSLog(@"-------------请求对应的产品信息----------------");
    NSArray *product = [[NSArray alloc] initWithObjects:type, nil ];
    
    NSSet *nsset = [NSSet setWithArray:product];
    SKProductsRequest *request = [[SKProductsRequest alloc] initWithProductIdentifiers:nsset];
    request.delegate = self;
    [request start];
    
}

//收到产品返回信息
- (void)productsRequest:(SKProductsRequest *)request didReceiveResponse:(SKProductsResponse *)response{
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    NSLog(@"--------------收到产品反馈消息---------------------");
    NSArray *product = response.products;
    if([product count] == 0){
        NSLog(@"--------------没有商品------------------");
        return;
    }
    
    NSLog(@"productID:%@", response.invalidProductIdentifiers);
    NSLog(@"产品付费数量:%zd",[product count]);
    
    SKProduct *p = nil;
    for (SKProduct *pro in product) {
        NSLog(@"%@", [pro description]);
        NSLog(@"%@", [pro localizedTitle]);
        NSLog(@"%@", [pro localizedDescription]);
        NSLog(@"%@", [pro price]);
        NSLog(@"%@", [pro productIdentifier]);
        
        if([pro.productIdentifier isEqualToString:@"com.thumb12341"]){
            p = pro;
        }
        
    }
    
    SKPayment *payment = [SKPayment paymentWithProduct:p];
    
    NSLog(@"发送购买请求");
    [[SKPaymentQueue defaultQueue] addPayment:payment];
}
//请求失败
- (void)request:(SKRequest *)request didFailWithError:(NSError *)error{
    NSLog(@"------------------错误-----------------:%@", error);
}

- (void)requestDidFinish:(SKRequest *)request{
    NSLog(@"------------反馈信息结束-----------------");
}


//监听购买结果
- (void)paymentQueue:(SKPaymentQueue *)queue updatedTransactions:(NSArray *)transaction{
    for(SKPaymentTransaction *tran in transaction){
        
        switch (tran.transactionState) {
            case SKPaymentTransactionStatePurchased:
                NSLog(@"交易完成");
                
                break;
            case SKPaymentTransactionStatePurchasing:
                NSLog(@"商品添加进列表");
                
                break;
            case SKPaymentTransactionStateRestored:
                NSLog(@"已经购买过商品");
                
                break;
            case SKPaymentTransactionStateFailed:
                NSLog(@"交易失败");
                
                break;
            default:
                break;
        }
    }
}
//交易结束
- (void)completeTransaction:(SKPaymentTransaction *)transaction{
    NSLog(@"交易结束");
    NSString * productIdentifier = transaction.payment.productIdentifier;
    NSLog(@"::::%@",productIdentifier);
    if ([productIdentifier length] > 0) {
        // 向自己的服务器验证购买凭证
    }
    [[SKPaymentQueue defaultQueue] finishTransaction:transaction];
}
- (void)failedTransaction:(SKPaymentTransaction *)transaction {
    if(transaction.error.code != SKErrorPaymentCancelled) {
        NSLog(@"购买失败");
    } else {
        NSLog(@"用户取消交易");
    }
    [[SKPaymentQueue defaultQueue] finishTransaction: transaction];
}


-(void)back{
    [self.navigationController popViewControllerAnimated:YES];
}
-(void)viewWillAppear:(BOOL)animated{
    [super viewWillAppear:animated];
    
    self.tabBarController.tabBar.hidden = YES;
    self.tabBarController.tabBar.translucent = YES;
    
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
